package key;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Mrename
 */
@WebServlet("/Mrename")
public class Mrename extends HttpServlet {
	private static final long serialVersionUID = 1L;

	Log log = new Log();
	Database db = new Database();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Mrename() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String oldName = request.getParameter("oldn");
		String newName = request.getParameter("newn");
		String uidS = null;
		int uid = 0;
		if (db.isExist(newName)) {
			
			/* 生成页面 */
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			response.setCharacterEncoding("utf-8");
			out.println("<html>\n<head>\n<title>提示信息</title>\n</head>\n<body>");
			out.println("<script type='text/javascript'>\nconfirm('" + newName +"已存在')");
			out.println("window.location.href='master/index.jsp';\n</script>");
			out.println("</body>\n</html>");
			
//			response.sendRedirect("master/index.jsp");
//			@SuppressWarnings("unused")
//			Frame fr = new Frame("新用户名已存在");
		} else {
			try {
				uidS = db.getUid(oldName);
			} catch (SQLException e) {
				log.writeIn("Mrename: 不存在此用户或页面出现错误0020");
			}
			if (uidS != null) {
				uid = Integer.parseInt(uidS);
				db.rename(uid, newName);

				/* 生成页面 */
				response.setContentType("text/html;charset=utf-8");
				PrintWriter out = response.getWriter();
				response.setCharacterEncoding("utf-8");
				out.println("<html>\n<head>\n<title>提示信息</title>\n</head>\n<body>");
				out.println("<script type='text/javascript'>\nconfirm('重命名成功')");
				out.println("window.location.href='master/index.jsp';\n</script>");
				out.println("</body>\n</html>");
				
//				response.sendRedirect("master/index.jsp");
//				@SuppressWarnings("unused")
//				Frame fr = new Frame("重命名完成");
			} else {
				/* 生成错误页面 */
				System.out.println("不存在此用户或页面出现错误");

				response.sendRedirect("master/index.jsp");
				@SuppressWarnings("unused")
				Frame fr = new Frame("不存在此用户或出现错误");
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
